package com.wk.warehouse.filter;

import com.wk.warehouse.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class AuthFilter implements Filter {

	@Override
	public void doFilter(ServletRequest req, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		User user = (User) request.getSession().getAttribute("user");
		String uri = request.getRequestURI();
		if(uri.endsWith(".action") && user == null 
				&& !uri.endsWith("login.action") && !uri.endsWith("validCode.action")){
			//没有登录
			response.setContentType("text/html;charset=UTF-8");
			response.getWriter().println("<script>alert('请登录！');location.href='"+request.getContextPath()+"/user/login.action';</script>");
			return;
		}else{
			//判断有没有权限
			if(uri.endsWith(".action") && !uri.endsWith("login.action") &&
					!uri.endsWith("validCode.action")){
				//获取当前用户拥有的权限
				String authUrls=request.getSession().getAttribute("authUrls")+"";
	    		if(!(authUrls.indexOf(uri)!=-1)){
	    			//没有权限
	    			response.setContentType("text/html; charset=UTF-8");
	    			response.getWriter().println("<script>alert('请登录！');location.href='"+request.getContextPath()+"/user/login.action';</script>");
	    			return;
	    		}
			}
		}
		chain.doFilter(req, response);
	}
}
